<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NSelect,
  NImage,
  NInput,
  NInputNumber,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  type UploadCustomRequestOptions,
  type FormInst,
  type FormItemRule,
  NSpace,
  NModal,
  NDatePicker,
  NCheckboxGroup,
  NCheckbox,
  NUpload,
  useDialog
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated, watchEffect, onMounted } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { RecordType } from '@/router/utils'
import QrcodeVue from 'qrcode.vue'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const formInfo: any = ref({
  conferenceRoomName: null
})

const StatusList = [
  {
    value: 1,
    label: '启用'
  },
  {
    value: 2,
    label: '停用'
  }
]

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '序号',
    key: 'sort',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '会议室名称',
    key: 'name',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: true,
    ellipsis: {
      tooltip: {
        contentStyle: 'max-width:200rem'
      }
    }
  },
  {
    title: '可容纳人数',
    key: 'suggestedNumber',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '内部设施',
    key: 'facility',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '现场图片',
    key: 'image',
    width: '10rem',
    align: useStore.isCenter,
    render(row: any) {
      return h(
        NImage,
        {
          height: 100,
          src: row.image,
          style: {
            cursor: 'pointer'
          },
          onClick: () => {}
        },
        { default: () => '' }
      )
    }
  },
  {
    title: '状态',
    key: 'status',
    width: '5rem',
    align: useStore.isCenter,
    render({ status }) {
      switch (status) {
        case true:
          return '启用'
        case false:
          return '停用'
      }
    }
  },

  {
    title: '操作',
    key: 'action',
    width: '15rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            handleEdit(e)
          }
        },
        {
          default: () => '修改'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleStatus(e)
        },
        {
          default: () => (e.status ? '停用' : '启用')
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDel(e)
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleCode(e)
        },
        {
          default: () => '二维码'
        }
      )
    ]
  }
]

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

// 添加重置函数
const resetQuery = () => {
  formInfo.value.conferenceRoomName = null
  queryTableData(true)
  message.success('查询条件已重置')
}
const isEditing = ref(false)
const editingId = ref(null)

const handleEdit = (e: any) => {
  isEditing.value = true
  editingId.value = e.id
  addFormVisiable.value = true
  const validFacilities = e.facility
    ? e.facility
        .split(',')
        .filter((facilityCode: string) => facilities.value.some((f) => f.dicName === facilityCode))
    : []
  // 填充表单数据
  formData.value = {
    name: e.name,
    suggestedNumber: e.suggestedNumber,
    status: e.status ? '1' : '2',
    facility: validFacilities,
    image: e.image
  }
  // 填充图片列表
  tasmpList.value = e.image
    ? [
        {
          id: e.id,
          name: 'CurrentImage',
          status: 'finished',
          url: e.image
        }
      ]
    : []
}

const dialog = useDialog()

const handleStatus = async (e: any) => {
  const action = e.status ? '停用' : '启用'
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomReservation',
    uri: {
      roomId: e.id
    }
  })

  if (error) {
    message.error(error.message || '获取预约数据失败')
    return
  }

  if (res.code === 0) {
    if (res.data) {
      if (e.status) {
        dialog.success({
          title: `确认${action}`,
          content: `该会议室有正在申请中/已通过的预定流程，确定停用吗？`,
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            changeRoomStatus(e.id, !e.status)
          }
        })
      } else {
        dialog.success({
          title: `确认${action}`,
          content: `您确定要${action}这个会议室吗？`,
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: () => {
            changeRoomStatus(e.id, !e.status)
          }
        })
      }
    } else {
      dialog.success({
        title: `确认${action}`,
        content: `您确定要${action}这个会议室吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          changeRoomStatus(e.id, !e.status)
        }
      })
    }
  } else {
    message.error('删除失败！')
  }
}

const changeRoomStatus = async (id: string, newStatus: boolean) => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomStatus',
    uri: {
      id: id
    }
  })

  if (error) {
    return message.error(error.message)
  }

  if (res.code === 0) {
    message.success(`会议室${newStatus ? '启用' : '停用'}成功`)
    queryTableData() // 刷新表格数据
  } else {
    message.error(res.msg || '操作失败')
  }
}

const handleDel = async (e: any) => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomReservation',
    uri: {
      roomId: e.id
    }
  })

  if (error) {
    message.error(error.message || '获取预约数据失败')
    return
  }

  if (res.code === 0) {
    if (res.data) {
      dialog.success({
        title: '确认删除',
        content: '该会议室有正在申请中/已通过的预定流程，确定删除吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          deleteRoom(e.id)
        }
      })
    } else {
      dialog.success({
        title: '确认删除',
        content: '您确定要删除这个会议室吗？此操作不可逆。',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          deleteRoom(e.id)
        }
      })
    }
  } else {
    message.error('删除失败！')
  }
}

const deleteRoom = async (id: number) => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomDel',
    uri: {
      id: id
    }
  })
  if (error) {
    return message.error(error.message)
  }
  if (res.code === 0) {
    message.success('会议室删除成功')
    queryTableData() // 刷新表格数据
  } else {
    message.error(res.msg || '删除失败')
  }
}

const qrCodeModal = ref(false)
const qrCodeUrl = ref('')
const baseUrl = import.meta.env.VITE_BASE_URL + 'mobile/#/meeting-reserve?id=' // 替换为您的实际基础URL

const handleCode = (e: any) => {
  qrCodeUrl.value = `${baseUrl}${e.id}`
  qrCodeModal.value = true
}

//申请
const handleAdd = () => {
  addFormVisiable.value = true
  // router.push({
  //   path: '/OA/Seal/SealApplicationAdd'
  // })
}

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Seal/SealApplicationDetail',
    query: {
      id: val.id
    }
  })
}

//撤回
const modalVisible = ref(false)
const modalId = ref()
const modalCode = ref()

const againBack = async () => {
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'sealApplicationBack',
    override: {
      params: {
        id: modalId.value,
        code: modalCode.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  queryTableData()
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomList',
    override: {
      params: {
        conferenceRoomName: formInfo.value.conferenceRoomName,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
  tableData.value.forEach((item: any, index: number) => {
    item.sort = index + 1
  })
}

// 新增弹窗
const addFormVisiable = ref(false)
const formRef = ref<FormInst | null>(null)
const formData = ref<any>({
  name: null,
  suggestedNumber: null,
  status: null,
  facility: null,
  image: null
})

const resetFormData = () => {
  formData.value = {
    name: null,
    suggestedNumber: null,
    status: null,
    facility: null,
    image: null
  }
  tasmpList.value = []
  isEditing.value = false
  editingId.value = null
  addFormVisiable.value = false
}

const statusOptions = [
  {
    value: '1',
    label: '启用'
  },
  {
    value: '2',
    label: '停用'
  }
]

const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入名称'
  },
  suggestedNumber: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入可容纳人数'
  },
  status: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择状态'
  },
  facility: {
    type: 'array',
    required: false,
    trigger: 'change',
    message: '请选择至少一个设施'
  },
  image: {
    required: false,
    trigger: 'change',
    message: '请上传图片'
  }
}

const facilities = ref<any>([])
const getFacilities = async () => {
  const [error, res] = await sendRequest({
    module: 'meeting',
    api: 'roomFacilities',
    override: {
      params: {
        dicCode: 'A70'
      }
    }
  })
  if (error) return message.error(error.message)
  facilities.value = res.data
}

onMounted(() => {
  getFacilities()
})

const imgHZ = ['jpg', 'png', 'jpeg']
const tasmpList = ref<any>([])
const commonUpload = async ({
  file,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  const tmp = file.name.split('.')
  if (!imgHZ.includes(tmp[tmp.length - 1])) return message.error('请上传图片类型'), onError()
  const fileData = new FormData()
  fileData.append('file', file.file as File)
  const [error, res] = await sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: fileData,
      onUploadProgress(v: any) {
        onProgress({ percent: Math.ceil(v.progress) })
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error('上传失败'), onError()
  tasmpList.value.push({
    id: res.data.fileId,
    name: res.data.name,
    status: 'finished',
    url: res.data.url
  })
  message.success('上传成功')
  // returnPictures()
  onFinish()
}

// 删除
const handleRemove = ({ file }: any) => {
  const index = tasmpList.value.findIndex((it: any) => it.name == file.name)
  tasmpList.value.splice(index, 1)
  message.success('删除成功')
  // returnPictures()
  return true
}

watch(
  () => tasmpList.value,
  () => {
    formData.value.image = tasmpList.value[0]?.url
  },
  {
    deep: true
  }
)

const handleSubmit = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate(async (errors: any) => {
    if (!errors) {
      const data: any = {}
      if (formData.value.facility) {
        data.facility = formData.value.facility.join(',') || null
      }
      data.status = formData.value.status == '1'
      data.image = formData.value.image
      data.name = formData.value.name
      data.suggestedNumber = formData.value.suggestedNumber

      let apiEndpoint = 'roomSave'
      if (isEditing.value) {
        apiEndpoint = 'roomEdit'
        data.id = editingId.value
      }

      const [error, res] = await sendRequest({
        module: 'meeting',
        api: apiEndpoint,
        override: {
          data
        }
      })
      if (error) {
        return message.error(error.message)
      }
      message.success(res.msg)
      resetFormData()
      queryTableData()
      isEditing.value = false
      editingId.value = null
    } else {
      message.error('提交失败，请检查表单')
    }
  })
}

const keyUpDown = (e: any) =>
  e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Meeting/RoomList') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
watch(
  () => addFormVisiable.value,
  (newValue) => {
    if (!newValue) {
      resetFormData()
    }
  }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="会议室名称:">
            <NInput
              v-model:value="formInfo.conferenceRoomName"
              clearable
            />
          </NFormItem>
          <!-- <NFormItem label="审批状态:">
            <NSelect
              v-model:value="formInfo.status"
              :options="StatusList"
              style="width: 150px"
              clearable
            />
          </NFormItem> -->
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px; margin-right: 40rem"
              @click="queryTableData(true)"
            >
              查询
            </NButton>
            <NButton
              type="primary"
              ghost
              style="width: 78px"
              @click="resetQuery"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
      />
    </template>

    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <n-modal
    v-model:show="qrCodeModal"
    title="会议室二维码"
  >
    <qrcode-vue
      :value="qrCodeUrl"
      :size="800"
      level="H"
    />
  </n-modal>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againBack"
      title="撤回提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要撤回吗?
      </div>
    </VDialogContent>
  </NModal>

  <NModal
    :auto-focus="false"
    v-model:show="addFormVisiable"
  >
    <div class="add-form">
      <div class="form-title">
        <span>{{ isEditing ? '编辑会议室' : '新增会议室' }}</span>
        <img
          src="@/assets/images/meeting_dialog_close.png"
          alt=""
          @click="addFormVisiable = false"
        />
      </div>
      <div class="form-content">
        <n-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="auto"
          label-placement="left"
          class="form-container"
        >
          <div class="form-left">
            <n-form-item
              label="名称"
              path="name"
            >
              <n-input
                v-model:value="formData.name"
                placeholder="请输入"
              />
            </n-form-item>
            <n-form-item
              label="可容纳人数"
              path="suggestedNumber"
            >
              <n-input-number
                v-model:value="formData.suggestedNumber"
                placeholder="请输入"
                :min="0"
                :precision="0"
              />
              <!-- <n-input
                v-model="formData.suggestedNumber"
                placeholder="请输入"
              /> -->
            </n-form-item>
            <n-form-item
              label="状态"
              path="status"
            >
              <n-select
                v-model:value="formData.status"
                placeholder="请输入"
                :options="statusOptions"
              ></n-select>
            </n-form-item>
            <n-form-item
              label="内部设施"
              path="facility"
            >
              <n-checkbox-group v-model:value="formData.facility">
                <n-checkbox
                  :value="item.dicName"
                  v-for="item in facilities"
                  :key="item.id"
                >
                  {{ item.dicName }}
                </n-checkbox>
              </n-checkbox-group>
            </n-form-item>
          </div>
          <div class="form-right">
            <n-form-item
              label="图片"
              path="image"
            >
              <n-upload
                list-type="image-card"
                :max="1"
                :custom-request="(e: any) => commonUpload(e)"
                :on-remove="handleRemove"
                :default-file-list="tasmpList"
              >
                <div class="meeting-upload"></div>
              </n-upload>
            </n-form-item>
            <span class="img-tip">建议使用1500*680分辨率的图片</span>
          </div>
        </n-form>
      </div>
      <div class="form-bottom">
        <n-button
          round
          @click="resetFormData"
        >
          取消
        </n-button>
        <n-button
          type="primary"
          round
          @click="handleSubmit"
        >
          确定
        </n-button>
      </div>
    </div>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
.add-form {
  position: relative;
  display: flex;
  width: 756px;
  height: 394px;
  flex-direction: column;
  align-items: flex-start;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0px 10px 32px 0px rgba(38, 38, 38, 0.18);
  .form-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 56px;
    padding: 0 24px;
    background: linear-gradient(180deg, #fff 0%, #f6f7fa 100%);
    color: #2d3339;
    font-size: 16px;
    font-weight: 600;
    line-height: 24px; /* 150% */
    border-radius: 8px 8px 0 0;
    img {
      width: 24px;
      height: 24px;
      cursor: pointer;
    }
  }
  .form-container {
    display: flex;
    flex-wrap: wrap;
    padding: 24px;
  }

  .form-left {
    flex: 1;
    min-width: 300px;
  }

  .form-right {
    flex: 1;
    min-width: 300px;
    display: flex;
    flex-direction: column;
    padding-left: 20px;
    .meeting-upload {
      width: 80px;
      height: 80px;
      background-image: url('@/assets/images/meeting_dialog_upload.png');
      background-size: 100%;
    }
    .img-tip {
      margin-left: 80px;
      color: #999;
    }
  }
  .form-bottom {
    position: absolute;
    bottom: 24px;
    right: 24px;
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    width: 100%;
  }
}
</style>
